package top.jacktgq.hsp.nio.buffer_channel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author CandyWall
 * @Date 2020/11/11--12:06
 * @Description 使用FileChannel向文件中写入数据
 */
public class NIOFileChannel01 {
    public static void main(String[] args) {
        String str = "hello，糖果墙";
        //创建一个输出流，用Channel包装
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File("tmp/file01.txt"));
            //通过FileOutputStream获取对应的Channel，真实类型是FileChannelImpl
            FileChannel fileChannel = fos.getChannel();

            //创建一个缓冲区 ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            //将str写入到byteBuffer中
            byteBuffer.put(str.getBytes());

            //对byteBuffer进行flip
            byteBuffer.flip();

            //将byteBuffer中的数据写入到fileChannel
            fileChannel.write(byteBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
